import axios from 'axios'
import Cookies from 'js-cookie'
import router from '@/router'
import whiteApiList from './whiteApi'
import { Message } from 'element-ui'
// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL,
  timeout: 5000 // request timeout
})

service.interceptors.request.use(
  config => {
    config.headers['Authorization'] = Cookies.get('TOKEN')
    config.headers['Content-type'] = 'application/json'
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(response => {
  if(response.data.code === 401 ) {
    Message({
      message: '登录令牌失效',
      type: 'error',
      duration: 2000
    })
    return router.push('/login')
  }
  return response.data
}, error => {
  // 和后端约定的3种状态码会跳转登录
  if (error.response.status && [400, 401, 403].includes(error.response.status)) {
    if (status === 400) {
      Message({
        message: '权限不足',
        type: 'error',
        duration: 2000
      })
    } else if (status === 401) {
      Message({
        message: '登录令牌失效',
        type: 'error',
        duration: 2000
      })
    }
    return router.push('/login')
  } else {
    return { code: '500', msg: '访问异常' }
  }
})

export const createAPI = (url, method, data, type) => {
  const config = {}
  config.headers = {
    'Content-Type': 'application/json'
  }
  if (method === 'get') {
    config.params = data
  } else {
    config.data = data
  }
  config.responseType = type

  return service({
    url,
    method,
    ...config
  })
}
export default createAPI
